<template>
	<div>
		<!-- 顶部选项卡 -->
		<scroll-view class="pagecontrol-top-scroll" scroll-x="true" scroll-with-animation
			:scroll-into-view="scrollInto">
			<view class="pagecontrol-top-title">
				<view v-for="(items, index) in itemsArr" :key="index" class="pagecontrol-top-text"
					@click="changeTab(index)" :id="'tab' + index">
					<view :class="tabIndex === index ? 'pagecontrol-top-selected' : 'pagecontrol-top-normal'">
						{{ items }}
					</view>
					<view class="pagecontrol-bottom-line"
						:class="tabIndex === index ? 'pagecontrol-bottom-line-show' : 'pagecontrol-bottom-line-visibility'">
					</view>
				</view>
			</view>
		</scroll-view>
		<!-- 内容 -->
		<swiper :duration="150" :current="tabIndex" @change="onChangeTab" :style="'height:' + scrollH + 'px;'">
			<swiper-item>
				<scroll-view scroll-y="true" show :style="'height:' + scrollH + 'px;'">
					<!--基本资料-->
					<view style="padding-bottom: 100px;">
						<view style="background-color: #ffffff;margin: 10px;border-radius: 12px;padding: 15px;">
							<uni-forms ref="form" :modelValue="formData" :rules="rules" labelWidth="90px">
								<view style="display: flex;">
									<view style="flex: 1;">
										<uni-forms-item label="车牌号码" name="licensePlate" required labelWidth="75px">
											<uni-easyinput type="text" v-model="formData.licensePlate" placeholder="车牌号码" />
										</uni-forms-item>
										<uni-forms-item label="车型" name="carType" required labelWidth="75px">
											<uni-data-select v-model="formData.carType" :localdata="carType"
												style="background-color: white;" />
										</uni-forms-item>
										<uni-forms-item label="车宽(米)" name="carWidth" required labelWidth="75px">
											<uni-easyinput type="text" v-model="formData.carWidth" placeholder="车宽(米)" />
										</uni-forms-item>
										<uni-forms-item label="载重(吨)" name="loadCapacity" required labelWidth="75px">
											<uni-easyinput type="text" v-model="formData.loadCapacity" placeholder="载重(吨)" />
										</uni-forms-item>
										<uni-forms-item label="车身颜色" name="color" required labelWidth="75px">
											<uni-data-select v-model="formData.color" :localdata="color"
												style="background-color: white;" />
										</uni-forms-item>
										<uni-forms-item label="运输用途" name="transportUsage" required labelWidth="75px">
											<uni-data-select v-model="formData.transportUsage" :localdata="transportUsage"
												style="background-color: white;" />
										</uni-forms-item>
									</view>
									<view style="flex: 1;">
										<!-- <uni-forms-item label="是否车头" name="headType" required  labelAlign="center" labelWidth="75px">
											<uni-data-select v-model="formData.headType" :localdata="headType"
												style="background-color: white;" />
										</uni-forms-item> -->
										<uni-forms-item label="车长(米)"  labelAlign="center" name="carLength" required labelWidth="75px">
											<uni-easyinput type="text" v-model="formData.carLength" placeholder="车长(米)" />
										</uni-forms-item>
										<uni-forms-item label="车高(米)" name="carHeight" labelAlign="center" labelWidth="75px">
											<uni-easyinput type="text" v-model="formData.carHeight" placeholder="车高(米)" />
										</uni-forms-item>
										<uni-forms-item label="体积(方)" name="volume" required labelAlign="center" labelWidth="75px">
											<uni-easyinput type="text" v-model="formData.volume" placeholder="体积(方)" />
										</uni-forms-item>
										<uni-forms-item label="运输油品" labelAlign="center" labelWidth="75px">
											<uni-data-select v-model="formData.energyType" :localdata="energyType"
												style="background-color: white;" />
										</uni-forms-item>
										<uni-forms-item label="价格(万)" name="purchasePrice" labelAlign="center" labelWidth="75px">
											<uni-easyinput type="text" v-model="formData.purchasePrice" placeholder="购买价格(万)" />
										</uni-forms-item>
									</view>
								</view>
								<uni-forms-item label="车主姓名" name="ownerName">
									<uni-easyinput type="text" v-model="formData.ownerName" placeholder="请输入车主姓名" />
								</uni-forms-item>
								<uni-forms-item label="联系电话" name="contactNumber">
									<uni-easyinput type="number" v-model="formData.contactNumber" placeholder="请输入联系电话" />
								</uni-forms-item>
								<uni-forms-item label="车主身份证" name="ownerIdCard">
									<uni-easyinput type="number" v-model="formData.ownerIdCard" placeholder="请输入身份证" />
								</uni-forms-item>
								<uni-forms-item label="品牌型号" name="brandType">
									<uni-easyinput type="number" v-model="formData.brandType" placeholder="请输入品牌型号" />
								</uni-forms-item>
								<uni-forms-item label="车辆识别代码" name="vin">
									<uni-easyinput type="text" v-model="formData.vin" placeholder="请输入车主识别代码" />
								</uni-forms-item>
								<uni-forms-item label="车主所在地址" name="ownerLocationDistrictId">
									<uni-data-picker placeholder="请选择地址" popup-title="请选择所在地区" :localdata="ownerLocationDistrictId"
										style="background-color: white;" v-model="formData.ownerLocationDistrictId">
									</uni-data-picker>
									<view style="margin-top: 20px;">
										<uni-easyinput  type="text"
											v-model="formData.ownerLocationAddress" placeholder="请输入详细地址" />
									</view>
								</uni-forms-item>
								<uni-forms-item label="相关资料">
									<myfilepicker :limit="'1'" :imageStyles="imageStyles" :fileIdString="formData.vehicleAttachment" :fileExtname="'png,jpg,jpeg'" :fileMediatype="'image'"  @transFileIdString="getFileIdString_vehicleAttachment"
											:title="'*点击上传行驶证，支持png/jpg/jpeg，最多可上传1个附件*'"><uni-icons type="cloud-upload" size="18"></uni-icons>行驶证</myfilepicker>
									<view style="margin-top: 10px;">
										<myfilepicker :limit="'1'" :imageStyles="imageStyles" :fileIdString="formData.carPicAttachment" :fileExtname="'png,jpg,jpeg'" :fileMediatype="'image'"  @transFileIdString="getFileIdString_carPicAttachment"
												:title="'*点击上传车辆照片，支持png/jpg/jpeg，最多可上传1个附件*'"><uni-icons type="cloud-upload" size="18"></uni-icons>车辆照片</myfilepicker>
									</view>
									<view style="margin-top: 10px;">
										<myfilepicker :limit="'3'"  :fileIdString="formData.otherAttachment" :fileExtname="'pdf,png,gif,jpg,jpeg,doc,docx'" :fileMediatype="'all'"  @transFileIdString="getFileIdString_otherAttachment"
												:title="'*点击上传其他附件，支持pdf/doc/docx/jpg/jpeg/png/gif，最多可上传3个附件*'"></myfilepicker>
									</view>
								    
								</uni-forms-item>
								<uni-forms-item label="备注" name="remark">
									<uni-easyinput type="textarea" v-model="formData.remark" placeholder="车辆相关备注说明" />
								</uni-forms-item>
							</uni-forms>
							
						</view>
						<!-- <view style="background-color: #ffffff;margin: 10px;border-radius: 12px;min-height: 400px;padding: 10px;">
							车辆定位->经度：{{formData.positionLng}} 纬度：{{formData.positionLat}}
							<map style="width: 100%; height: 300px;" latitude="39.909" longitude="116.39742" :markers="[{latitude: '39.909',longitude:'116.39742',iconPath: '../../../static/logo.png'}]"></map>
						</view> -->
					</view>
				</scroll-view>
				<view
					style="background-color: #ffffff;z-index: 3;height: 70px;width:100%;position: fixed;bottom: 0;display: flex;box-shadow: 0px 0px 11px rgba(0, 0, 0, 0.1);">
					<view
						style="display: flex;align-items: center;width: 100%;height: 60px;justify-content: center;">
						<view v-if="carId==''" @click="submit()" hover-class="buttonHover"
							style="height: 35px;background-color: #bf5f09;color: #ffffff;width: 100px;display: flex;justify-content: center;align-items: center;border-radius: 4px;">
							确定新增</view>
						<view v-else @click="submit_update()" hover-class="buttonHover"
							style="height: 35px;background-color: #bf5f09;color: #ffffff;width: 100px;display: flex;justify-content: center;align-items: center;border-radius: 4px;">
							保存</view>
					</view>
				</view>
			</swiper-item>
			<swiper-item>
				<scroll-view scroll-y="true" show :style="'height:' + scrollH + 'px;'">
					<!--关联司机-->
					<view style="padding-bottom: 100px;">
						<view>
							<radio-group @change="radioChange">
								<label v-for="(item, index) in driverList" :key="item.value" style="display: flex;flex-direction: column;background-color: white;padding: 15px;border-bottom: 1rpx solid #ededed;" >
									<view style="display: flex;justify-content: space-between;">
										<text>{{item.carrierDriver.driverName}}</text>
										<text style="margin-left: 20px;">{{item.carrierDriver.phoneNumber}}</text>
										<text v-if="item.carrierDriver.sex=='0'">男</text>
										<text v-else-if="item.carrierDriver.sex=='1'">女</text>
										<text v-else>未知</text>
										<text>{{item.carrierDriver.licenseType}}</text>
										<text>{{item.carrierDriver.drivingYears}}年</text>
										<text v-if="item.carrierDriver.ownVehicle==0">加盟</text>
										<text v-else>自有</text>
									</view>
									<view style="position: relative;margin-top: 10px;">
										<view style="display: flex;justify-content: space-between;">
											<text style="color:#a5a5a5;">驾照到期日：{{item.carrierDriver.driverLicenseExpireDate}}</text>
											<view style="margin-right: 70px;">
												<radio :value="index" :checked="item.mainDriver==='1'" />
												<text>设为主驾</text>
											</view>
										</view>
										<button @click="deleteDriverList(index)" hover-class="buttonHover" type="primary"
											style="position: absolute;width: 60px;text-align: center;right: 0;top:0;color:#ffffff;border-radius: 8px;font-size: 13px;background-color: #bf5f09;">移除</button>
									</view>
								</label>
							</radio-group>
						</view>
						<!-- <view @click="addDriverList" hover-class="buttonHover" style="position: fixed;left: 50%;transform:translateX(-50%);bottom:10px;width: 100px;height:35px;color:#ffffff;background-color:#bf5f09;border-radius: 4px;display:flex;justify-content: center;align-items: center;">
							设置司机
						</view> -->
						<view @click="addDriverList" hover-class="buttonHover" style="position: fixed;right: 15px;bottom:100px;width: 50px;height:50px;color:#ffffff;background-color:#bf5f09;border-radius: 50%;display:flex;justify-content: center;align-items: center;box-shadow: 0 1px 5px 2px rgba(0, 0, 0, 0.3);">
							<uni-icons type="plusempty" size="30" color="#ffffff"></uni-icons>
						</view>
					</view>
				</scroll-view>
				<view
					style="background-color: #ffffff;z-index: 3;height: 70px;width:100%;position: fixed;bottom: 0;display: flex;box-shadow: 0px 0px 11px rgba(0, 0, 0, 0.1);">
					<view
						style="display: flex;align-items: center;width: 100%;height: 60px;justify-content: center;">
						<view v-if="carId==''" @click="submit()" hover-class="buttonHover"
							style="height: 35px;background-color: #bf5f09;color: #ffffff;width: 100px;display: flex;justify-content: center;align-items: center;border-radius: 4px;">
							确定新增</view>
						<view v-else @click="submit_update()" hover-class="buttonHover"
							style="height: 35px;background-color: #bf5f09;color: #ffffff;width: 100px;display: flex;justify-content: center;align-items: center;border-radius: 4px;">
							保存</view>
					</view>
				</view>
			</swiper-item>
		</swiper>
		
		<!-- 设置司机弹窗 -->
		<uni-popup ref="alertDialog" type="dialog">
			<uni-popup-dialog type="info" cancelText="关闭" confirmText="确定" title="设置司机" @confirm="dialogConfirm">
				<scroll-view scroll-top="0" scroll-y="true" style="height: 200px;">
					<view style="display: flex;flex-direction: column;width: 100%;">
						<uni-data-checkbox  mode="button" multiple v-model="driver" :localdata="allDriverList"></uni-data-checkbox>
					</view>
				</scroll-view>
			</uni-popup-dialog>
		</uni-popup>
	</div>
</template>

<script>
	import {
		getCarDetails,
		addCar,
		updateCarProfile
	} from '@/api/system/car.js'
	import {getDriverList} from '@/api/system/driver.js'
	import {getDicts,getAllAddressTree} from '@/api/system/dict.js'
	import myfilepicker from '@/components/uploadFile/uploadFile.vue'
	
	export default {
		components: {
			myfilepicker
		},
		data() {
			return {
				itemsArr: ['基本资料', '关联司机'],
				tabIndex: 0,
				scrollH: 700,
				scrollInto: '',
				formData: {
					licensePlate: '',
					carType:'',
					carWidth:'',
					loadCapacity: '',
					color: '',
					transportUsage: '',
					headType: '',
					carLength:'',
					carHeight:'',
					volume:'',
					energyType:'',
					purchasePrice:'',
					ownerName:'',
					contactNumber:'',
					ownerIdCard:'',
					brandType:'',
					vin:'',
					ownerLocationDistrictId:'',
					ownerLocationAddress:'',
					
					vehicleAttachment:'',
					carPicAttachment:'',
					otherAttachment:'',
					
					remark: '',
				},
				// 校验规则
				rules: {
					licensePlate: {
						rules: [{
							required: true,
							errorMessage: '请输入车牌号码',
						}]
					},
					carType: {
						rules: [{
							required: true,
							errorMessage: '请选择车型',
						}]
					},
					carWidth: {
						rules: [{
							required: true,
							errorMessage: '请输入车宽',
						}]
					},
					loadCapacity: {
						rules: [{
							required: true,
							errorMessage: '请输入载重',
						}]
					},
					color: {
						rules: [{
							required: true,
							errorMessage: '请选择车身颜色',
						}]
					},
					transportUsage: {
						rules: [{
							required: true,
							errorMessage: '请选择运输用途',
						}]
					},
					headType: {
						rules: [{
							required: true,
							errorMessage: '请选择是否车头',
						}]
					},
					carLength: {
						rules: [{
							required: true,
							errorMessage: '请输入车长',
						}]
					},
					volume: {
						rules: [{
							required: true,
							errorMessage: '请输入体积',
						}]
					}
				},
				//地区下拉框
				ownerLocationDistrictId: [],
				//下拉框 ->车型
				carType: [],
				//下拉框 ->车辆颜色
				color: [],
				//下拉框 ->运输用途
				transportUsage: [],
				//下拉框 ->是否车头
				headType: [],
				//下拉框 ->能源类型
				energyType: [],
				imageStyles: {
					width: '100%',
					height: 200,
					border: {
						radius: '4px'
					}
					
				},
				// 关联司机
				driverList: [],
				carId:'',
				//关联司机的用户
				allDriverList:[],
				driver:[],
			}
		},
		onLoad(e) {
			uni.getSystemInfo({
				success: res => {
					this.scrollH = res.windowHeight - 40;
				}
			});
			
			if (e.carId) {
				//设置顶部导航栏标题
				uni.setNavigationBarTitle({
					title: '编辑车辆'
				})
			
				uni.showLoading({
					title: '正在加载',
				})
				this.carId = e.carId
				//获取车辆详情
				getCarDetails(e.carId).then(res => {
					uni.hideLoading()
					if (res.code == '200') {
						this.formData = res.data
						this.driverList=this.formData.driverList||[]
					} else {
						uni.showToast({
							icon: 'none',
							title: res.msg
						})
					}
				})
			}
		},
		created() {
			//获取车型下拉框
			getDicts('car_type').then(res=>{
				this.carType=res.data.map(item=>{
					return {
						value:item.dictValue,
						text:item.dictLabel
					}
				})
			})
			
			//获取车辆颜色下拉框
			getDicts('car_color').then(res=>{
				this.color=res.data.map(item=>{
					return {
						value:item.dictValue,
						text:item.dictLabel
					}
				})
			})
			
			//获取运输用途下拉框
			getDicts('transport_usage').then(res=>{
				this.transportUsage=res.data.map(item=>{
					return {
						value:item.dictValue,
						text:item.dictLabel
					}
				})
			})
			
			//获取车头类型下拉框
			getDicts('head_type').then(res=>{
				this.headType=res.data.map(item=>{
					return {
						value:item.dictValue,
						text:item.dictLabel
					}
				})
			})
			
			//获取能源类型下拉框
			getDicts('energy_type').then(res=>{
				this.energyType=res.data.map(item=>{
					return {
						value:item.dictValue,
						text:item.dictLabel
					}
				})
			})
			
			//获取全国地址信息->地区下拉框
			getAllAddressTree().then(res=>{
				this.ownerLocationDistrictId=res.data
			})
		},
		methods: {
			//接收文件传递的id字符串集合
			getFileIdString_vehicleAttachment(fileIds){
				this.formData.vehicleAttachment=fileIds
			},
			//接收文件传递的id字符串集合
			getFileIdString_carPicAttachment(fileIds){
				this.formData.carPicAttachment=fileIds
			},
			//接收文件传递的id字符串集合
			getFileIdString_otherAttachment(fileIds){
				this.formData.otherAttachment=fileIds
			},
			// 切换选项
			changeTab(index) {
				if (this.tabIndex === index) {
					return;
				}
				this.tabIndex = index;
				// 滚动到指定元素
				this.scrollInto = 'tab' + index;
			},
			// 监听滑动
			onChangeTab(e) {
				uni.showLoading({
					title: '正在加载',
				})
				setTimeout(function() {
					uni.hideLoading()
				}, 500);
				this.changeTab(e.detail.current);
			},
			//选择关联司机
			radioChange(e) {
				//设置为主驾
				this.driverList.forEach((item,index)=>{
					if(e.detail.value==index) //选择的序列设为主驾
					{
						item.mainDriver='1'
					}
					else
					{
						item.mainDriver='0'
					}
				})
			},
			//移除关联司机
			deleteDriverList(index){
				let that = this
				uni.showModal({
					title: '提示',
					content: '确定删除此条数据？',
					success: function (res) {
						if (res.confirm) {
							that.driverList.splice(index,1)
						}
					}
				});
			},
			//添加关联司机按钮
			addDriverList(){
				getDriverList({pageNum:1,pageSize:1000}).then(res=>{
					this.allDriverList=res.rows.map(item=>{
						let flag=false
						this.driverList.forEach(item2=>{
							if(item2.driverId==item.driverId)
							{
								flag=true
							}
						})
						return {
							value:JSON.stringify(item),
							text:item.driverName+' '+item.phoneNumber+' '+(item.ownVehicle==='0'?'加盟':'自有')+' '+(item.sex==='0'?'男':(item.sex==='1'?'女':'未知'))+' '+item.licenseType,
							disable: flag
						}
					})
				})
				this.$refs.alertDialog.open()
			},
			//确认设置关联司机
			dialogConfirm() {
				if(this.driver.length)
				{
					this.driver.forEach(item=>{
						let driver=JSON.parse(item)
						this.driverList.push({
							value: driver.driverId,
							name: driver.driverName,
							driverId:driver.driverId,
							carrierDriver:driver,
							mainDriver:'0',
						})
					})
				}
				
			},
			//提交新增车辆
			submit() {
				let that = this
				this.$refs.form.validate().then(res => {
					let mainDriver=false
					this.driverList.forEach(item=>{
						if(item.mainDriver=='1')
						{
							mainDriver=true
						}
					})
					// if(!mainDriver)
					// {
					// 	uni.showToast({
					// 		title: '请在【关联司机】中设置一名主驾',
					// 		icon:'none'
					// 	})
					// 	return
					// }
					
					uni.showLoading({
						title: '正在提交...',
					})
					
					//关联司机
					let driverList=this.driverList.map(item=>{
						return{
							carrierDriver:item.carrierDriver,
							driverId:item.driverId,
							mainDriver:item.mainDriver
						}
					})
					this.formData.driverList=driverList
					
					addCar(that.formData).then(res => {
						uni.hideLoading()
						if (res.code == '200') {
							uni.showToast({
								title: '提交成功',
								icon: 'none'
							})
							let pages = getCurrentPages(); // 获取当前页面栈的实例，以数组形式按栈的顺序给出，第一个元素为首页，最后一个元素为当前页面。
							let nowPage = pages[pages.length - 1]; //当前页页面实例
							let prevPage = pages[pages.length - 2]; //上一页页面实例
							prevPage.$vm.otherFun('4') // 給上一頁綁定方法otherFun,傳參0（tabIndex：0）
							uni.navigateBack({
								delta: 1 // 可以不傳delta值，默認為1
							})
						} else {
							uni.showToast({
								icon: 'none',
								title: res.msg
							})
						}
					})
				}).catch(err => {
					uni.showToast({
						title: err[0].errorMessage,
						icon: 'none'
					})
				})
			},
			//修改车辆
			submit_update() {
				let that = this
				this.$refs.form.validate().then(res => {
					
					let mainDriver=false
					this.driverList.forEach(item=>{
						if(item.mainDriver=='1')
						{
							mainDriver=true
						}
					})
					// if(!mainDriver)
					// {
					// 	uni.showToast({
					// 		title: '请在【关联司机】中设置一名主驾',
					// 		icon:'none'
					// 	})
					// 	return
					// }
			
					uni.showLoading({
						title: '正在提交...',
					})
					
					//关联司机
					let driverList=this.driverList.map(item=>{
						return{
							carId:this.carId,
							carrierDriver:item.carrierDriver,
							driverId:item.driverId,
							mainDriver:item.mainDriver
						}
					})
					this.formData.driverList=driverList

					that.formData.carId = that.carId
					updateCarProfile(that.formData).then(res => {
						uni.hideLoading()
						if (res.code == '200') {
							uni.showToast({
								title: '修改成功',
								icon: 'none'
							})
							let pages = getCurrentPages(); // 获取当前页面栈的实例，以数组形式按栈的顺序给出，第一个元素为首页，最后一个元素为当前页面。
							let nowPage = pages[pages.length - 1]; //当前页页面实例
							let prevPage = pages[pages.length - 2]; //上一页页面实例
							prevPage.$vm.otherFun('4') // 給上一頁綁定方法otherFun,傳參0（tabIndex：0）
							setTimeout(() => {
								uni.navigateBack({
									delta: 1 // 可以不傳delta值，默認為1
								})
							}, 1000)
						} else {
							uni.showToast({
								icon: 'none',
								title: res.msg
							})
						}
					})
				}).catch(err => {
					uni.showToast({
						title: err[0].errorMessage,
						icon: 'none'
					})
				})
			},
		},
	}
</script>

<style scoped>
	.pagecontrol-top-scroll {
		height: 40px;
		width: 100%;
		white-space: nowrap;
		box-sizing: border-box;
		border-bottom: 1rpx solid #ededed;
		background-color: #f8f8f8;
	}

	.pagecontrol-top-title {
		height: 100%;
		width: 100%;
		display: flex;
		justify-content: space-around;
	}

	.pagecontrol-top-text {
		height: 100%;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		text-align: center;
	}

	.pagecontrol-top-normal {
		color: #656565;
		font-size: 16px;
	}

	.pagecontrol-top-selected {
		color: #000000;
		font-weight: bold;
		font-size: 16px;
	}

	.pagecontrol-bottom-line {
		width: 50vw;
		height: 3px;
		margin-top: 8px;
		background-color: #bf5f09;
		border-radius: 11px;
	}

	.pagecontrol-bottom-line-show {
		visibility: visible;
	}

	.pagecontrol-bottom-line-visibility {
		visibility: hidden;
	}

	.buttonHover {
		opacity: 0.6;
	}
	::v-deep .file-title{
	    font-size: 12px;
	    color: #333;
	}
	
	::v-deep .uni-select__input-box{
		width: 0vw;
	}
</style>